package com.iot.ammeter.view.custom

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import com.iot.ammeter.R

/**
 * 可带文本的分割线
 * @see [R.styleable.Divider]
 */
class Divider(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private val textPaint: Paint
    private val linePaint: Paint
    private var fontSize: Float
    var text: String

    init {
        context.obtainStyledAttributes(attrs, R.styleable.Divider).also {
            text = it.getString(R.styleable.Divider_text) ?: "文本"
            val defaultColor = Color.GRAY
            fontSize = it.getDimension(R.styleable.Divider_fontSize, 18F)
            textPaint = TextPaint().apply {
                color = it.getColor(R.styleable.Divider_textColor, defaultColor)
                textSize = fontSize
            }

            linePaint = Paint().apply {
                color = it.getColor(R.styleable.Divider_lineColor, defaultColor)
                strokeWidth = it.getDimension(R.styleable.Divider_strokeWidth, 2F)
            }
        }.recycle()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val measure = textPaint.measureText(text)
        val textHeight = -linePaint.ascent()
        val halfOfHeight = height / 2F
        val leftStopX = (width - measure) / 2
        val rightStartX = (width + measure) / 2
        val space = fontSize / 1.8F
        // 绘制文本左右的分割线
        canvas.drawLine(0F, halfOfHeight, leftStopX - space, halfOfHeight, linePaint)
        canvas.drawLine(rightStartX + space, halfOfHeight, width.toFloat(), halfOfHeight, linePaint)
        // 绘制中间文本
        canvas.drawText(text, leftStopX, (height + textHeight) / 2, textPaint)
    }

}
